package com.qtt.app.service.impl;

import com.qtt.app.entity.*;
import com.qtt.app.entity.ReturnInfo.ReturnCommentCourse;
import com.qtt.app.mapper.*;
import com.qtt.app.service.OrderFormService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

import static com.qtt.app.utils.Converter.getAsBigDecimal;
import static com.qtt.app.utils.Converter.getAsLong;
import static com.qtt.app.utils.JSONUtils2.objectToJsonStr;
import static com.qtt.app.utils.RandomUtils.*;

@Service
public class OrderFormServiceImpl implements OrderFormService {
    @Autowired
    OrderFormMapper orderFormMapper;
    @Autowired
    AppCommentMapper appCommentMapper;
    @Autowired
    GeneralCourseMapper generalCourseMapper;
    @Autowired
    ExactCourseMapper exactCourseMapper;
    @Autowired
    TeachersMapper teachersMapper;
    @Autowired
    RegisteredCourseMapper registeredCourseMapper;
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    CourseClassMapper courseClassMapper;

    @Override
    public List<OrderForm> listAll() {
        List<OrderForm> entities = orderFormMapper.list();
        return entities;
    }

    @Override
    public List<OrderForm> getOrderByIdAndState(Long userId, Integer orderState) {
        //如果是要查全部,则只传用户id即可
        if(orderState == 0 ){
            List<OrderForm> entities = orderFormMapper.getOrderByUserId(userId);
            return entities;
        }
        else {
            List<OrderForm> entities2 = orderFormMapper.getOrderByIdAndState(userId, orderState);
            return entities2;
        }

    }

    //获取到报名的课程，并显示是否评论
    @Override
    public List<ReturnCommentCourse> getCommentCourse(Long userId, int orderState) {
        List<OrderForm> orderFormEntities = orderFormMapper.getOrderByIdAndState(userId, orderState);
        List<ReturnCommentCourse> returnCommentCourseEntities = new ArrayList<ReturnCommentCourse>();
        ReturnCommentCourse returnCommentCourseEntity = new ReturnCommentCourse();
        for(int i = 0 ; i < orderFormEntities.size() ; i++) {
            OrderForm orderFormEntity = orderFormEntities.get(i);
            //首先取出订单中的课程id，到课程表中查询到那条记录，并拿出相应字段
            String courseId = orderFormEntity.getCourseId();
            String generalId = courseId.substring(0, courseId.length() - 1);//generalId为courseId去掉最后一位
            GeneralCourse generalCourseEntity = generalCourseMapper.selectByPrimaryKey(generalId);//因为所要字段在genenral表中即可拿到就不用去遍历appcourse表了
            returnCommentCourseEntity.setCourseId(courseId);
            returnCommentCourseEntity.setCourseTitle(generalCourseEntity.getTitle());
            returnCommentCourseEntity.setCoursePicture(generalCourseEntity.getMainPicture());
            //课程状态需要结合exact-course表进行判断，拿取opentime，与现在时间比较
            ExactCourse exactCourseEntity = exactCourseMapper.getExactCourseByCourseId(courseId);
            Date openTime = exactCourseEntity.getOpeningTime();
            returnCommentCourseEntity.setCourseState(null);

            //课程教师需要结合老师表。teacher从general表拿出
            Integer teacherId = generalCourseEntity.getTeacherId();
            System.out.println(teacherId);
            returnCommentCourseEntity.setTeacherId(teacherId);
            Teachers teacherEntity = teachersMapper.selectByPrimaryKey(teacherId);
            returnCommentCourseEntity.setTeacherName(teacherEntity.getRealName());

            //评论状态需要结合appcomment表
            String orderId = orderFormEntity.getId();
            returnCommentCourseEntity.setOrderId(orderId);
            AppComment appCommentEntity = appCommentMapper.getCommentByUserAndOrderId(userId,orderId);
            if(appCommentEntity==null){
                returnCommentCourseEntity.setIsComment(false);//该课程订单没有评论
                returnCommentCourseEntity.setCommentId(null);
                returnCommentCourseEntity.setAppCommentId(null);
                returnCommentCourseEntities.add(returnCommentCourseEntity);

            }
            else {
                returnCommentCourseEntity.setIsComment(true);//该课程订单没有评论
                returnCommentCourseEntity.setCommentId(appCommentEntity.getCommentId());
                returnCommentCourseEntity.setAppCommentId(appCommentEntity.getAppcommentId());
                returnCommentCourseEntities.add(returnCommentCourseEntity);//添加进列表
            }

        }
        return returnCommentCourseEntities;
    }

    @Override
    public int payOrder(Long userId, String generalId, String realName, String phone, BigDecimal realPrice, BigDecimal sumPrice,Integer peopleNum,Integer flag) {
        GeneralCourse generalCourseEntity = generalCourseMapper.selectByPrimaryKey(generalId);
        System.out.println(generalId+"1");
        ExactCourse exactCourseEntity = exactCourseMapper.selectByPrimaryKey(generalId+"1");
        String payNo = getOrderPayNoRandom();
        String orderId = getOrderIdRandom();
//        BigDecimal sumPrice=realPrice.multiply(getAsBigDecimal(peopleNum));

        //需要先生成一条reg_course记录
        RegisteredCourse registeredCourseEntity = new RegisteredCourse();
        registeredCourseEntity.setCourseId(generalId+"1");
        registeredCourseEntity.setTeacherId(generalCourseEntity.getTeacherId());
        registeredCourseEntity.setUserId(userId);
        registeredCourseEntity.setStaff(exactCourseEntity.getStaffId());
        registeredCourseEntity.setStatus(1);
        registeredCourseEntity.setPeopleNum(peopleNum);
        registeredCourseEntity.setVersion(404);
        registeredCourseEntity.setGmtCreate(new Date());
        registeredCourseEntity.setGmtModified(null);
        int addRegFlag = registeredCourseMapper.insert(registeredCourseEntity);
        Integer regId = registeredCourseMapper.getLastId();

        //生成一条comment记录
        Comment commentEntity = new Comment();
        commentEntity.setUserId(userId);
        commentEntity.setStatus(0);
        commentEntity.setCourseId(generalId);//原来lk将courseId设成了generalId，这里就讲错就错了。
        int addCommentFlag = commentMapper.insert(commentEntity);
        Integer commentId = commentMapper.getLastId();
        //生成一条app_comment记录


        //取出刚插入的那条记录的regid，添加到order表
        OrderForm orderFormEntity = new OrderForm();
        orderFormEntity.setId(orderId);//id必须要有，因为不是自增,工具类随机生成
        if (flag == 1) {
            orderFormEntity.setStatus(1);//支付直接状态变1,表示还未付钱
        }
        if(flag == 2){
            orderFormEntity.setStatus(2);//支付直接状态变2
        }
        orderFormEntity.setCourseId(generalId+"1");
        orderFormEntity.setGeneralId(generalId);
        orderFormEntity.setUserId(userId);
        orderFormEntity.setSumPrice(sumPrice);
        orderFormEntity.setRealPrice(realPrice);
        orderFormEntity.setPayTime(new Date());
        orderFormEntity.setPayNo(payNo);
        orderFormEntity.setRealName(realName);
        orderFormEntity.setPhone(phone);
        orderFormEntity.setShareId(getAsLong(0));
        orderFormEntity.setPeopleNum(peopleNum);
        orderFormEntity.setRegId(regId);
        orderFormEntity.setGmtCreate(new Date());
        orderFormEntity.setGmtModified(null);
        //将order表的version重新赋予新的意义，即学习进度 ；所以每次创建订单即传入进度为0
        //        orderFormEntity.setVersion(404);
        orderFormEntity.setVersion(null);
//        CourseClass courseClassEntity = courseClassMapper.getCourseClassByCourseId(generalId);
//        Integer totalClassNum = courseClassEntity.getClassHour();
//        Integer alreadyStudyNum = 0;
//        Map<String,Object> versionMap = new HashMap<>();
//        versionMap.put("totalClassNum",totalClassNum);
//        versionMap.put("alreadyStudyNum",alreadyStudyNum);
//        String JsonStr = objectToJsonStr(versionMap);
//        orderFormEntity.s

        //修改exact表的购买数量
        ExactCourse updateExactCourseEntity = new ExactCourse();
        updateExactCourseEntity.setId(generalId+"1");
        updateExactCourseEntity.setBuyNum(exactCourseEntity.getBuyNum()+peopleNum);
        exactCourseMapper.updateByPrimaryKeySelective(updateExactCourseEntity);

        int addOrderFlag = orderFormMapper.insert(orderFormEntity);
        return addOrderFlag;
    }


}
